package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.NoticeService;
import com.qdlc.p2p.biz.sms.SmsProtalProviderChooser;
import com.qdlc.p2p.biz.util.mail.Mail;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.NoticeTypeHelper;
import com.qdlc.p2p.dal.common.NoticeTypeHelper.NidType;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.MessageDao;
import com.qdlc.p2p.dal.dao.NoticeDao;
import com.qdlc.p2p.dal.dao.UserCacheDao;
import com.qdlc.p2p.dal.dao.UserNoticeConfigDao;
import com.qdlc.p2p.dal.dto.Message;
import com.qdlc.p2p.dal.dto.Notice;
import com.qdlc.p2p.dal.dto.NoticeType;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.model.NoticeModel;
import com.qdlc.p2p.dal.util.SystemConfigs;
import com.qdlc.p2p.dal.util.UserUtils;

@Service("noticeService")
public class NoticeServiceImpl implements NoticeService {

    private Logger logger = Logger.getLogger(NoticeServiceImpl.class);

    @Resource
    private NoticeDao noticeDao;

    @Resource
    private MessageDao messageDao;

    @Resource
    private UserNoticeConfigDao userNoticeConfigDao;

    @Resource
    private UserCacheDao userCacheDao;


    @Override
    public void sendNotice(Notice notice) {
        switch (Byte.parseByte(notice.getType())) {
            case NoticeTplNid.NOTICE_SMS:
                this.sendSms(notice);
                break;
            case NoticeTplNid.NOTICE_EMAIL:
                this.sendEmail(notice);
                break;
            case NoticeTplNid.NOTICE_MESSAGE:
                this.sendMessage(notice);
                break;
        }
    }

    private void sendSms(Notice s) {

        String mobile = s.getReceiveAddr();
        String content = StringUtil.isNull(s.getContent());

        logger.debug("contentString=========" + content);
        logger.debug("mobile=========" + mobile);

        // 如果没有为短信配置特殊的send_route则直接通过默认的短信通道发送
        NoticeType smsType = NoticeTypeHelper.getValue(s.getNid(), NidType.NOTICE_SMS);
        String sendRoute = smsType.getSendRoute();
        SmsProtalProviderChooser.SmsResult smsResult = SmsProtalProviderChooser.choice(sendRoute).send(mobile, content);
        if (smsResult.isSuccess()) {
            s.setStatus(1);
        } else {
            s.setStatus(0);
        }
        s.setResult(smsResult.getMessage());
        logger.info(smsResult.getMessage());
        noticeDao.save(s);
    }

    private void sendEmail(Notice notice) {
        Mail mail = Mail.getInstance();
        mail.setTo(notice.getReceiveAddr());
        mail.setSubject(notice.getTitle());
        mail.setBody(notice.getContent());
        try {
            mail.sendMail();
            notice.setStatus(1);
            notice.setResult("ok");
            logger.debug("发送邮件成功！！");
        } catch (Exception e) {
            notice.setStatus(0);
            notice.setResult("fail");
            logger.error("发送邮件失败", e);
        }

        noticeDao.save(notice);
    }

    private void sendMessage(Notice s) {
        Message m = new Message();
        m.setTitle(s.getTitle());
        m.setSentUserId(s.getSentUserId());
        m.setReceiveUserId(s.getReceiveUserId());
        m.setContent(s.getContent());
        m.setAddTime(DateUtil.getNow());
        m.setAddIp(Global.getIP());
        messageDao.insert(m);

        s.setStatus(1);
        s.setResult("ok");
        noticeDao.save(s);
    }

    // 在系统发送且用户接收的情况下再进行这个发送判断
    private boolean isSmssend(NoticeType noticeType, UserCache userCache, User user) {
        boolean smssend = false;

        // 手机激活验证码肯定发送
        if (noticeType.getNid().equalsIgnoreCase("phone_code")) {
            smssend = true;
            return smssend;
        }

        // 手机没认证不能发送
        /*
         * if (1 != user.getPhone_status()){ return smssend; }
		 */

        // 系统短信也发送
        if (noticeType.getType() == Constant.SYSTEM_NOTICE) {
            smssend = true;
        } else {
            // 用户短信需要付费
            /*
             * long smspayEndtime = userCache.getSmspay_endtime(); if (smspayEndtime > DateUtil.getTime(DateUtil.getNow())) {
			 * smssend = true; }
			 */
        }

        return smssend;
    }

    @Override
    public PageDataList<NoticeModel> noticeList(NoticeModel model, int pageNumber, int pageSize) {
        QueryParam param = QueryParam.getInstance().addPage(pageNumber, pageSize);
        if (!StringUtil.isBlank(model.getSearchName())) {//模糊查询条件
            SearchFilter orFilter1 = new SearchFilter("title", Operators.LIKE, model.getSearchName().trim());
            /*SearchFilter orFilter2 = new SearchFilter("sentUser.userName", Operators.LIKE, model.getSearchName().trim());*/
            SearchFilter orFilter3 = new SearchFilter("receiveUser.userName", Operators.LIKE, model.getSearchName().trim());
            param.addOrFilter(orFilter1, orFilter3);
        } else { //精确查询条件
            if (!StringUtil.isBlank(model.getTitle())) {
                param.addParam("title", Operators.LIKE, model.getTitle());
            }
            if (StringUtil.isNotBlank(model.getType()) && !"99".equals(model.getType())) {
                param.addParam("type", model.getType());
            }
            if (model.getStatus() != 99) {
                param.addParam("status", model.getStatus());
            }
        }
        param.addOrder(OrderType.DESC, "id");
        PageDataList<Notice> plist = noticeDao.findPageList(param);

        PageDataList<NoticeModel> uList = new PageDataList<NoticeModel>();
        uList.setPage(plist.getPage());
        List<NoticeModel> list = new ArrayList<NoticeModel>();
        if (plist.getList().size() > 0) {
            for (int i = 0; i < plist.getList().size(); i++) {
                Notice notice = (Notice) plist.getList().get(i);
                NoticeModel noticeModel = NoticeModel.instance(notice);
                User sentUser = UserUtils.getUserById(notice.getSentUserId());
                User receiveUser = UserUtils.getUserById(notice.getReceiveUserId());
                if (sentUser != null) {
                    if (sentUser.getUserId() == SystemConfigs.ADMIN_ID) {
                        noticeModel.setSentName(SystemConfigs.WEB_NAME);
                    } else {
                        noticeModel.setSentName(sentUser.getUserName());
                    }
                }
                //如果用户为空，则把接收地址设置成用户名
                if (null == receiveUser) {
                    noticeModel.setReceiveName(notice.getReceiveAddr() + "『注册』");
                } else {
                    noticeModel.setReceiveName(receiveUser.getUserName());
                }
                list.add(noticeModel);
            }
        }
        uList.setList(list);
        return uList;
    }

    @Override
    public Notice findById(long id) {

        return noticeDao.find(id);
    }

    @Override
    public void sendNotice(String receiveAddr, String type, String noticeId,
                           String code) {
        NoticeService noticeService = (NoticeService) BeanUtil.getBean("noticeService");

        // 注册验证码模版
        Map<String, Object> sendData = new HashMap<String, Object>();

        NoticeType smsType = NoticeTypeHelper.getValue(noticeId, NidType.NOTICE_SMS);
        smsType.setSend(1);
        sendData.put("code", code);
        sendData.put("vtime", SystemConfigHelper.getValue(Nid.VERIFY_CODE_TIME));
        sendData.put("webname", SystemConfigs.WEB_NAME);
        //获取 注册验证码 短信模版内容
        if (StringUtil.equals(type, NoticeTplNid.PHONE_SEND)) {           //短信发送验证码
            sendData.put("phone", receiveAddr);
            if (smsType.getSend() == NoticeTplNid.NOTICE_SEND) {
                //封装notice类
                Notice notice = new Notice();
                notice.setTitle(StringUtil.fillTemplet(smsType.getTitleTemplet(), sendData));
                notice.setNid(noticeId);
                notice.setType(String.valueOf(NoticeTplNid.NOTICE_SMS));
                notice.setReceiveAddr(receiveAddr);
                notice.setContent(StringUtil.fillTemplet(smsType.getTemplet(), sendData));
                notice.setAddTime(DateUtil.getNow());
                //发送短信方法
                noticeService.sendNotice(notice);
            }
        }

        if (StringUtil.equals(type, NoticeTplNid.EMAIL_SEND)) {  //邮箱发送验证码
            sendData.put("web_name", SystemConfigs.WEB_NAME);
            sendData.put("web_url", SystemConfigHelper.getValue(Nid.WEB_URL));
            sendData.put("mail", receiveAddr);
            User user = new User();
            user.setUserName(receiveAddr);
            sendData.put("user", user);
            sendData.put("noticeTime", SystemConfigHelper.getValue(Nid.VERIFY_CODE_TIME));
            NoticeType emailType = NoticeTypeHelper.getValue(noticeId, NidType.NOTICE_EMAIL);
            if (smsType.getSend() == NoticeTplNid.NOTICE_SEND) {
                Notice notice = new Notice();
                notice.setTitle(StringUtil.fillTemplet(emailType.getTitleTemplet(), sendData));
                notice.setNid(noticeId);
                notice.setType(String.valueOf(NoticeTplNid.NOTICE_SMS));
                notice.setReceiveAddr(receiveAddr);
                notice.setContent(StringUtil.fillTemplet(emailType.getTemplet(), sendData));
                notice.setAddTime(DateUtil.getNow());
                sendEmail(notice);
            }
        }
    }
}